﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Guna.UI2.WinForms;
using LiveCharts.Wpf;
using LiveCharts.Defaults;
using LiveCharts;

namespace UI_Scripts2
{
    public partial class UCinbox_notes : UserControl
    {
        private Api api;
        DateTime today = DateTime.Now;  //当前日期
        int daysAmount;                 //用户要求显示的天数
        List<UserNotes> userNotes;      //给定天数内的所有小记

        //用于字数统计的数据
        string[] xlabels;  //折线图的x坐标
        Dictionary<int, int> dailyWordsAmount = new Dictionary<int, int>(0); //每天小记的字数
        int[] WordsValues; //存储字典dailyWordsAmount中的值

        //用于情感极性分析的数据
        Dictionary<int, int> dailySentiment = new Dictionary<int, int>(0); //每天的情感极性
        int[] SentiValues; //存储字典dailySentiment中的值
        float avrgSenti = 0; //平均情感极性

        public int NoteID;

        public UCinbox_notes()  //构造函数
        {
            InitializeComponent();
            AddingNotePanel.Visible = false;
            AnalysisPanel.Visible = true;
            solidGauge1.From = 0;
            solidGauge1.To = 2;

            api = new Api();
            
            daysAmount = (int)DaysAmount.Value-1; //用户要求显示的天数
            userNotes = api.GetUserNotesAsync(Api.Token, daysAmount); //给定天数内的所有小记

            WordsAmountShow();
            SentiShow();
            NotesShow();
        }

        private void StartAddButton_Click(object sender, EventArgs e) //开始添加一条小记
        {
            if (StartAddButton.Text == "+") //add panel
            {
                groupBox1.Visible = false;
                showNotes.Visible = false;
                AddingNotePanel.Visible = true;
                AddingNotePanel.Location = new Point(-417, 31);
                DateTimePicker.Value = DateTime.Now;
                timer1.Start();
            }
            else //cancel
            {
                timer1.Start();
            }
        }

        private void AddButton_Click(object sender, EventArgs e) //确认添加或更新小记
        {
            string content = NotesTextBox.Text;
            int wordcount = NotesTextBox.Text.Length;
            DateTime date = DateTimePicker.Value;
            
            PostNote postNote = new PostNote(content, wordcount, date, Api.Token);

            //调用api
            if (AddButton.Text == "ADD NOTE")
            {
                string state = api.PostUserNotesAsync(postNote);
                if (state == "Created")
                {
                    timer1.Start();
                    MessageBox.Show("Post succeed");
                    NotesTextBox.Clear();
                    AmountLabel.Text = "Words Amount: 0";
                    userNotes = api.GetUserNotesAsync(Api.Token, daysAmount); //给定天数内的所有小记
                    WordsAmountShow();
                    SentiShow();
                    NotesShow();
                    NotesTextBox.Clear();
                }
                else
                    MessageBox.Show(state);
            }
            else if (AddButton.Text == "UPDATE NOTE")
            {
                string state = api.PutUserNotesAsync(Api.Token, NoteID, postNote);
                if (state == "OK")
                {
                    timer1.Start();
                    MessageBox.Show("Update succeed");
                    NotesTextBox.Clear();
                    AmountLabel.Text = "Words Amount: 0";
                    AddButton.Text = "ADD";
                    userNotes = api.GetUserNotesAsync(Api.Token, daysAmount); 
                    WordsAmountShow();
                    SentiShow();
                    NotesShow();
                }
                else
                    MessageBox.Show(state);
            }
        }

        private int loc_x = -417;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (StartAddButton.Text == "+") //add panel
            {
                if (loc_x < 4)
                {
                    loc_x += 20;
                    AddingNotePanel.Location = new Point(loc_x, 31);
                    StartAddButton.Location = new Point(loc_x + 417, 568);
                }
                else
                {
                    StartAddButton.Text = "×";
                    timer1.Stop();
                    NotesTable.Visible = false;
                    return;
                }
            }
            else
            {
                if (loc_x > -417)
                {
                    loc_x -= 20;
                    AddingNotePanel.Location = new Point(loc_x, 31);
                    StartAddButton.Location = new Point(loc_x + 417, 568);
                }
                else
                {
                    StartAddButton.Text = "+";
                    timer1.Stop();
                    AddingNotePanel.Visible = false;
                    groupBox1.Visible = true;
                    showNotes.Visible = true;
                    NotesTable.Visible = true;
                    NotesTextBox.Clear();
                    AmountLabel.Text = "Words Amount: 0";
                    AddButton.Text = "ADD";
                    return;
                }
            }
        }

        public void WordsAmountShow()  //显示字数统计
        {
            xlabels = new string[daysAmount];
            WordsValues = new int[daysAmount];

            //为xlabels赋值
            for(int i = 0; i < daysAmount; i++)
            {
                System.TimeSpan duration = TimeSpan.Parse(-i + ".00:00:00");
                System.DateTime answer = today.Add(duration);
                dailyWordsAmount[answer.Day] = 0;
                xlabels[daysAmount - i - 1] = answer.Day.ToString();
                WordsValues[daysAmount - i - 1] = 0;
            }

            //为dailyWordsAmount赋值
            foreach (var userNote in userNotes)
                dailyWordsAmount[userNote.Date.Day] += userNote.Wordcount;

            //为WordsValue赋值
            int index = 0;
            foreach (var i in dailyWordsAmount)
            {
                WordsValues[daysAmount-index-1] = i.Value; index++;
            }

            cartesianChart1.AxisX.Clear();
            cartesianChart1.AxisY.Clear();
            cartesianChart1.AxisX.Add(new Axis
            {
                Title = "Days",
                Labels = xlabels
            });
            cartesianChart1.AxisY.Add(new Axis
            {
                Title = "Word Counts",
                LabelFormatter = value => value.ToString()
            });
            cartesianChart1.LegendLocation = LegendLocation.Bottom;
            cartesianChart1.Series = new SeriesCollection
            {
                new LineSeries
                {
                    Title = "字数",
                    Values = new ChartValues<int>(WordsValues),
                    LineSmoothness = 0,
                    PointGeometrySize = 10
                }
            };
        }

        public void SentiShow()  //显示情感极性分析
        {
            xlabels = new string[daysAmount];
            SentiValues = new int[daysAmount];

            //计算平均情感极性
            avrgSenti = 0;
            foreach (var userNote in userNotes)
                avrgSenti += userNote.Sentiment;
            avrgSenti /= userNotes.Count();

            //计算每日情感极性
            //为xlabels赋值
            for (int i = 0; i < daysAmount; i++)
            {
                System.TimeSpan duration = TimeSpan.Parse(-i + ".00:00:00");
                System.DateTime answer = today.Date.Add(duration);
                dailySentiment[answer.Day] = 0;
                xlabels[daysAmount - i - 1] = answer.Day.ToString();
                SentiValues[daysAmount - i - 1] = 0;
            }

            //为dailySentiment赋值
            foreach (var userNote in userNotes)
                dailySentiment[userNote.Date.Day] += userNote.Sentiment;

            //为SentiValues赋值
            int index = 0;
            foreach (var i in dailySentiment)
            {
                SentiValues[daysAmount - index - 1] = i.Value; index++;
            }
            
            solidGauge1.Value = Math.Round(avrgSenti,2);

            cartesianChart2.AxisX.Clear();
            cartesianChart2.AxisY.Clear();
            cartesianChart2.AxisX.Add(new Axis
            {
                Title = "Days",
                Labels = xlabels
            });
            cartesianChart2.AxisY.Add(new Axis
            {
                Title = "Sentiment Value",
                LabelFormatter = value => value.ToString()
            });
            cartesianChart2.LegendLocation = LegendLocation.Bottom;
            cartesianChart2.Series = new SeriesCollection
            {
                new LineSeries
                {
                    Title = "情感极性",
                    Values = new ChartValues<int>(SentiValues),
                    LineSmoothness = 0,
                    PointGeometrySize = 10
                }
            };
        }

        public void NotesShow()  //显示小记流水
        {
            NotesTable.Controls.Clear();
            foreach (var userNote in userNotes)
            {
                NoteCell noteCell = new NoteCell();

                noteCell.NoteID = userNote.Id;
                
                noteCell.WordsAmountLabel.Text = "字数: " + userNote.Wordcount.ToString();
                noteCell.TimeLabel.Text = userNote.Date.ToString();
                noteCell.ContentTextBox.Text = userNote.Content;
                noteCell.SentiLabel.Text = "情感倾向: ";
                if(userNote.Sentiment == 1)
                {
                    noteCell.SentiLabel.Text += "中性";
                }else if(userNote.Sentiment == 2)
                {
                    noteCell.SentiLabel.Text += "积极";
                }
                else
                {
                    noteCell.SentiLabel.Text += "负面";
                }
                noteCell.TagLabel.Text = "关键词: " + userNote.Tags;

                NotesTable.Controls.Add(noteCell); //加入到NotesTable中
                noteCell.Dock = DockStyle.Top;
            }
        }

        private void showNotes_Click(object sender, EventArgs e)  //更新显示的天数
        {
            daysAmount = (int)DaysAmount.Value-1; //用户要求显示的天数
            userNotes = api.GetUserNotesAsync(Api.Token, daysAmount); //给定天数内的所有小记
            dailyWordsAmount = new Dictionary<int, int>(0);
            dailySentiment = new Dictionary<int, int>(0);

            //再次调用饼图、折线图、流水显示函数
            WordsAmountShow();
            SentiShow();
            NotesShow();
        }

        private void NotesTextBox_TextChanged(object sender, EventArgs e)
        {
            int wordcount = NotesTextBox.Text.Length;
            AmountLabel.Text = "Words Amount: " + wordcount.ToString();
        }

        private void CloseButton_Click(object sender, EventArgs e)
        {
            MainPage mainPage = (MainPage)CloseButton.Parent.Parent.Parent;
            mainPage.timer1.Start();
        }
    }
}
